package com.ajhlp.app.phoneDetailQuery.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ajhlp.app.phoneDetailQuery.model.MatchResult;
import com.ajhlp.app.phoneDetailQuery.rule.Rule;
import com.ajhlp.app.phoneDetailQuery.rule.RuleQueryCondition;
import com.ajhlp.app.phoneDetailQuery.service.IPhoneRuleService;
import com.ajhlp.app.phoneDetailQuery.service.PhoneNumMatchRuleService;
import com.ajhlp.app.phoneDetailQuery.service.PhoneNumMatchRuleThread;

@Controller
public class RuleConfigController {
	
	private Logger log = Logger.getLogger(getClass());
	
	
	private static MatchResult MATCH_RESULT = null;
	
	@Resource
	private IPhoneRuleService ruleService;
	
	
	public IPhoneRuleService getRuleService() {
		return ruleService;
	}


	public void setRuleService(IPhoneRuleService ruleService) {
		this.ruleService = ruleService;
	}

	@Resource
	private PhoneNumMatchRuleService matchRuleService;
	

	public PhoneNumMatchRuleService getMatchRuleService() {
		return matchRuleService;
	}


	public void setMatchRuleService(PhoneNumMatchRuleService matchRuleService) {
		this.matchRuleService = matchRuleService;
	}


	@RequestMapping(value="/rules",method=RequestMethod.GET)
	public String listRules(final ModelMap model, RuleQueryCondition condition){
		List<Rule> rules = null;
		
		try {
			rules = ruleService.searchRule(condition);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			log.error("search rule error", e);
		}
		
		if(condition.getRule_fuzzy() != null){
			condition.setRule_fuzzy(condition.getRule_fuzzy().substring(0, condition.getRule_fuzzy().length()-1));
		}
		
		model.put("condition", condition);
		
		model.put("rules", rules);
		
		return "bg/rules";
	}
	
	@RequestMapping(value="/rule",method=RequestMethod.GET)
	public String addRule(){
		return "bg/addRule";
	}
	
	@RequestMapping(value="/rule/update",method=RequestMethod.POST)
	@ResponseBody
	public String updateRule(Rule rule,final ModelMap model){
		
		try {
			ruleService.updateRule(rule);
			return "{\"success\":\"true\",\"msg\":\"o(∩∩)o...哈哈\"}";
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			return "{\"success\":\"false\",\"msg\":\""+e.getMessage()+"\"}";
		}
		
	}
	
	@RequestMapping(value="/rule/add",method=RequestMethod.POST)
	public String addRule(Rule rule,final ModelMap model){
		
		if(rule.getRule() == null || rule.getRule().trim().equals("")){
			model.put("success", false);
			return "bg/addRule";
		}
		
		try {
			ruleService.saveRule(rule);
			model.put("success", true);
			return "bg/addRule";
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			model.put("success", false);
			return "bg/addRule";
		}
		
	}
	
	@RequestMapping(value="/rule/{rule}",method=RequestMethod.GET)
	@ResponseBody
	public String deleteRule(@PathVariable String rule){
		
		try {
			ruleService.deleteRule(rule);
			
			return "{\"success\":\"true\",\"msg\":\"o(∩∩)o...哈哈\"}";
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			log.error("删除号码规则失败",e);
			return "{\"success\":\"false\",\"msg\":\""+e.getMessage()+"\"}";
		}
		
	}
	
	@RequestMapping(value="/rule/{rule}",method=RequestMethod.POST)
	@ResponseBody
	public String isRuleExist(@PathVariable String rule){
		
		try {
			RuleQueryCondition condition = new RuleQueryCondition();
			condition.setRule(rule);
			
			int num = ruleService.searchRule(condition).size();
			
			if(num > 0){
				return "{\"success\":\"true\",\"result\":\"true\"}";
			}else{
				return "{\"success\":\"true\",\"result\":\"false\"}";
			}
			
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			log.error("查询号码规则是否存在失败",e);
			return "{\"success\":\"false\"}";
		}
		
	}
	
	@RequestMapping(value="/rule/match",method=RequestMethod.GET)
	public String getMatchResult(final ModelMap model){
		if(MATCH_RESULT != null){
			
			if(MATCH_RESULT.isMatching()){
				model.put("percent", MATCH_RESULT.getPercent());
			}
			
			if(MATCH_RESULT.isSuccess()){
				model.put("percent", "100%");
			}else{
				model.put("msg", MATCH_RESULT.getMsg());
			}
		}
		return "bg/matchRule";
	}
	
	@RequestMapping(value="/rule/match",method=RequestMethod.POST)
	@ResponseBody
	public String searchMultiQuery(HttpServletRequest request){
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart){
			return "0";
		}
		
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		BufferedReader br = null;
		// Parse the request
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(request);
			
			Iterator<FileItem> item = items.iterator();
			
			while (item.hasNext()) {
			    FileItem tmp = item.next();

			    if (tmp.isFormField()) {
			        
			    } else {
			       List<String> mobile = new ArrayList<String>();
			       
			       br = new BufferedReader(new InputStreamReader(tmp.getInputStream()));
			       
			       String phoneNum = "";
			       
			       while((phoneNum = br.readLine()) != null){
			    	   mobile.add(phoneNum);
			       }
			       Thread t = new Thread(new PhoneNumMatchRuleThread(this,matchRuleService, mobile, tmp.getName()));
			       t.start();
			    }
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "0";
		} finally {
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
		}
		return "1";
	}
	
	public void onMatch(boolean status,String percent,boolean success, String msg){
		if(MATCH_RESULT == null){
			MATCH_RESULT = new MatchResult(status,success,percent,msg);
		}else{
			MATCH_RESULT.setMatching(status);
			MATCH_RESULT.setPercent(percent);
			MATCH_RESULT.setSuccess(success);
			MATCH_RESULT.setMsg(msg);
		}
	}
}
